<?php
/**
* @description 通用函数库
*/

/**
 * 邮件发送
 *
 * @param: $name[string]        接收人姓名
 * @param: $email[string]       接收人邮件地址
 * @param: $subject[string]     邮件标题
 * @param: $content[string]     邮件内容
 * @param: $type[int]           0 普通邮件， 1 HTML邮件
 * @param: $notification[bool]  true 要求回执， false 不用回执
 *
 * @return boolean
 */
function sendMail($name, $email, $subject, $content, $type = 0, $notification=false)
{
    $charset='utf8';
	$smtp_mail='yourmail@163.com';
	/* 邮件的头部信息 */
	$content_type = ($type == 0) ?
		'Content-Type: text/plain; charset=' . $charset : 'Content-Type: text/html; charset=' . $charset;
	$content   =  base64_encode($content);

	$headers = array();
	$headers[] = 'Date: ' . gmdate('D, j M Y H:i:s') . ' +0000';
	$headers[] = 'To: "' . '=?' . $charset . '?B?' . base64_encode($name) . '?=' . '" <' . $email. '>';
	$headers[] = 'From: "' . '=?' . $charset . '?B?' . base64_encode('趣游管理后台') . '?='.'" <' . $smtp_mail. '>';
	$headers[] = 'Subject: ' . '=?' . $charset . '?B?' . base64_encode($subject) . '?=';
	$headers[] = $content_type . '; format=flowed';
	$headers[] = 'Content-Transfer-Encoding: base64';
	$headers[] = 'Content-Disposition: inline';
	if ($notification)
	{
		$headers[] = 'Disposition-Notification-To: ' . '=?' . $charset . '?B?' . base64_encode('趣游管理后台') . '?='.'" <' . $smtp_mail . '>';
	}

	$params['host'] = 'smtp.163.com';
	$params['port'] = '25';
	$params['user'] = 'yourmail';
	$params['pass'] = 'yourpassword';

	if (empty($params['host']) || empty($params['port']))
	{
		// 如果没有设置主机和端口直接返回 false
		return false;
	}
	else
	{
		// 发送邮件
		if (!function_exists('fsockopen'))
		{
			return false;
		}
		include_once('smtp.php');
		static $smtp;

		$send_params['recipients'] = $email;
		$send_params['headers']    = $headers;
		$send_params['from']       = $smtp_mail;
		$send_params['body']       = $content;

		if (!isset($smtp))
		{
			$smtp = new smtp($params);
		}
		if ($smtp->connect()&& $smtp->send($send_params))
			return true;
		return false;
	}  
}

//加载一个模板文件 包含公共头尾
function template($path, $vars=null)
{
	if(is_array($vars))
	{
		extract($vars);
	}
	include(ROOT.'/views/common/header.php');
	include(ROOT.'/views/'.$path.'.php');
	include(ROOT.'/views/common/footer.php');
}

//加载一个模板文件 不包含公共头尾
function stemplate($path, $vars=null)
{
	if(is_array($vars))
	{
		extract($vars);
	}
	include(ROOT.'/views/'.$path.'.php');
}

//返回一相模型对象
function loadModel($model)
{
	static $models=array();
	$model=strtolower($model);
	if($models[$model])
	{
		return $models[$model];
	}
	$file = ROOT.'/models/'.$model.'.class.php';
	if(!file_exists($file)) 
	{
		return false;
	}
	
	require_once $file;
	$amodel = $model.'Model';
	$obj = new $amodel();
	$models[$model]=$obj;
	return $obj;
}

//实例化一个简单model类,如果model类文件已经存在,则直接用models目录下已经存在的类
function instanceModel($tblname,$prefix=null)
{
	$obj=loadModel($tblname);
	if($obj)
	{
		return $obj;
	}
	else 
	{
		$file = ROOT.'/models/model.class.php';
		if(!file_exists($file)) 
		{
			return false;
		}
		require_once $file;
		return new Model($tblname,$prefix);
	}
}
//返回一个数据库对象
function loadMysql($group='mysql',$dbinterface=DB_INTERFACE)
{
	if($dbinterface=='pdo')
	{
		require_once(ROOT.'/include/ezsqlpdo.class.php');
		$db=ezSQLPdo::getInstance($group);
	}
	else
	{
		require_once(ROOT.'/include/ezsqlmysql.class.php');
		$db=ezSQLMysql::getInstance($group);
	}
	return $db;
}

//返回一个本站链接
function getUrl($str, $ext='')
{
	$baseurl=$_SERVER['PHP_SELF'];
	if($str == '' || $str == '/')
	{
		//$str='/';
		$str = $baseurl;
	}
	else
	{
		//$str = '/?r='.$str.'&'.$ext;
		$str = $baseurl.'?r='.$str.'&'.$ext;
	}
	return $str;
}

//转向
function redirect($url, $ext='')
{
	header('Location:'.getUrl($url, $ext));
	exit;
}

//由于单一入口的原因，表单的action项基本失效，用此函数在表单内输出一个隐藏表单表示提交地址,此机制待修改
function formAction($str)
{
	return '<input type="hidden" name="r" value="'.$str.'" />';
}
function htmlSelect($stitle,$array,$sval='',$event='')
{
	$str='<select id="'.$stitle.'" name="'.$stitle.'"'.($event?' '.$event:'').'>';
	foreach($array as $k=>$v)
	{
		if(!$k)
		{
			$k=0;
		}
		$str.='<option value="'.$k.'"'.($k==$sval?' selected':'').'>'.$v.'</option>';
	}
	$str.='</select>';
	return $str;
}
function htmlSelect2($stitle,$arr,$idfield,$titlefield,$sval='',$event='')
{
	$str='<select id="'.$stitle.'" name="'.$stitle.'"'.($event?' '.$event:'').'>';
	if(is_array($arr))
	{
		foreach($arr as $a)
		{
			if(is_array($a))
			{
				$str.='<option value="'.$a[$idfield].'"'.($a[$idfield]==$sval?' selected':'').'>'.$a[$titlefield].'</option>';
			}
		}
	}
	$str.="</select>";
	return $str;
}
//是否post模式提交
function isPost()
{
	return ($_SERVER['REQUEST_METHOD'] == 'POST');
}

//异常终止提示
function ex($message)
{
	echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
	echo '<table border="0" width="500" cellspacing="1" bgcolor="#333333"><tr><td bgcolor="#ccccff"><b>错误:</b></td></tr><tr><td bgcolor="#cccccc" style="padding:10px">'.$message.'</td></tr></table>';
	exit;
}

//通用获取参数
function get($key=null)
{
	$return = array();
	if(isset($_SERVER['PATH_INFO']))
	{
		$pathinfoStr = trim($_SERVER['PATH_INFO'],'/');
		if(!empty($pathinfoStr))
		{
			$pathinfo = explode('/',$pathinfoStr);
		}
		$return['pathinfo'] = $pathinfo;
	}
	$return = array_merge($return,$_GET);
	if($key===null)
	{
		return $return;
	}
	elseif(is_int($key))
	{
		if(isset($return['pathinfo'][$key]))
		{
			return $return['pathinfo'][$key];
		}
		else
		{
			return '';
		}
	}
	else
	{
		$return[$key] = (get_magic_quotes_gpc()) ? stripslashes($return[$key]) : $return[$key];
		if(is_array($return[$key]))
		{
			foreach($return[$key] as $k => $v)
			{
				$return[$key][$k] = trim($v);
			}
		}
		else
		{
			$return[$key] = trim($return[$key]);
		}
		if(isset($return[$key]))
		{
			return $return[$key];
		}
		else
		{
			return '';
		}
	}
}

function post($key=null,$callback='')
{
	if($key===null)
	{
		if($callback)
		{
			$func=create_function('&$item,$key','$item=$callback($item);');
			array_walk_recursive($_POST,$func);
		}
		return $_POST;
	}
	else
	{
		if(isset($_POST[$key]))
		{
			if(is_array($_POST[$key]))
			{
				foreach($_POST[$key] as $k => $v)
				{
					$_POST[$key][$k] = $callback?$callback(trim($v)):trim($v);
				}
			}
			else
			{
				$_POST[$key] = $callback?$callback(trim($_POST[$key])):trim($_POST[$key]);
			}
			return $_POST[$key];
		}
		else
		{
			return '';
		}
	}
}
function request($key=null,$callback='')
{
	if($key===null)
	{
		if($callback)
		{
			$func=create_function('&$item,$key','$item=$callback($item);');
			array_walk_recursive($_REQUEST,$func);
		}
		return $_REQUEST;
	}
	else
	{
		if(isset($_REQUEST[$key]))
		{
			if(is_array($_REQUEST[$key]))
			{
				foreach($_REQUEST[$key] as $k => $v)
				{
					$_REQUEST[$key][$k] = $callback?$callback(trim($v)):trim($v);
				}
			}
			else
			{
				$_REQUEST[$key] = $callback?$callback(trim($_REQUEST[$key])):trim($_REQUEST[$key]);
			}
			return $_REQUEST[$key];
		}
		else return '';
	}
}
// 得到当前客户端的IP
function ip() 
{
	if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) 
	{
		$ip = getenv("HTTP_CLIENT_IP");
	}
	elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) 
	{
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	}
	elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) 
	{
		$ip = getenv("REMOTE_ADDR");
	}
	elseif (isset($_SERVER["REMOTE_ADDR"]) && $_SERVER["REMOTE_ADDR"] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) 
	{
		$ip = $_SERVER["REMOTE_ADDR"];
	}
	else
   	{
		$ip = "0.0.0.0";
	}
	return $ip;
}

function isLogin()
{
	return isset($_COOKIE['admin_uid']);
}

function loginInfo($key)
{
	$key = 'admin_'.$key; //防止与前台cookie冲突，统一加上前辍
	if(isset($_COOKIE[$key]))
	{
		return $_COOKIE[$key];
	}
	else
	{
		return false;
	}
}

//获取flash图表
function getOfc($div_id, $data_url, $width=600, $height=400)
{
	$html = <<<HTML
	<div id="{$div_id}"></div>
	<script type="text/javascript">
	var params = {'wmode':'transparent'};
	var attributes = {};
	var flashvars = {'data-file':"{$data_url}"};
	swfobject.embedSWF("static/swf/open-flash-chart.swf", "{$div_id}", "{$width}", "{$height}", "8.0.0", false, flashvars, params, attributes);
	</script>
HTML;
	return $html;
}


//得到一个格式化的树形数据
function formatTreeData($data, $parent_id=0, $parent_name='index', $offset=0)
{
	$rt = array();
	if(is_array($data))
	{
		foreach($data as $k => $v)
		{
			if($v['fparent_id'] == $parent_id)
			{
				$tmp = $v;
				$tmp['parent_name'] = $parent_name;
				$tmp['child'] = formatTreeData($data, $tmp['fid'],$tmp['fname_en'], ($offset+1));
				$tmp['offset'] = $offset;
				$rt[] = $tmp;
			}
		}
	}
	return $rt;
}

function treeSelect($data,$sid=0)
{
	$str = '';
	if(is_array($data))
	{
		foreach($data as $v)
		{
			$offset_str = '';
			for($i = 0; $i< $v['offset']; $i++)
			{
				$offset_str .= '|---';
			}
			$str .= '<option value="'.$v['fid'].'"'.($v['fid']==$sid?' selected':'').'>'.$offset_str.$v['fname_en'].'</option>';
			$str .= treeSelect($v['child']);
		}
	}
	return $str;
}

function treeUi($data, $is_admin=false)
{
	$str = '<ul>';
	if(is_array($data))
	{
		foreach($data as $v)
		{
			if($is_admin)
			{
				$admin = '&nbsp;&nbsp;<a href="'.getUrl('auth/functionedit').'&id='.$v['fid'].'">修改</a>&nbsp;&nbsp;<a href="'.getUrl('auth/functiondel').'&id='.$v['fid'].'" class="del">删除</a>';
				$name = $v['fname_en'].' ('.$v['fname_cn'].')';
			}
			else
			{
				$admin = '';
				$name = ($v['fname_cn']) ? $v['fname_cn'] : $v['fname_en'];
			}

			if(empty($v['child']))
			{
				$str .= '<li><span class="file"><a class="menu" href="'.getUrl($v['parent_name'].'/'.$v['fname_en']).'"'.($is_admin?'':' target="ContentFrame"').'>'.$name.'</a>'.$admin.'</span></li>';
			}
			else
			{
				$str .= '<li><span class="folder">'.$name.$admin.'</span>';
				$str .= treeUi($v['child'], $is_admin);
				$str .= '</li>';
			}
		}
	}
	$str .= '</ul>';
	return $str;
}

function treeMenu($data)
{
	if(is_array($data))
	{
		foreach($data as $k=>$v)
		{
			$str.='<li>';
			$name=$v['fname_cn']?$v['fname_cn']:$v['fname_en'];
			//$str.='<a href="'.getUrl($v['parent_name'].'/'.$v['fname_en']).'" class="title" target="ContentFrame">'.$name.'</a>';
			$str.='<a href="#" class="title">'.$name.'</a>';
			if($v['child'])
			{
				$str.='<ul class="optiton">';
				foreach($v['child'] as $vv)
				{
					$str .= '<li><a href="'.getUrl($vv['parent_name'].'/'.$vv['fname_en']).'" target="ContentFrame">'.($vv['fname_cn']?$vv['fname_cn']:$vv['fname_en']).'</a></li>';
				}
				$str.='</ul>';
			}
			$str.='</li>';
		}
		return $str;
	}	
	return ;
}

function treeTable($data)
{
	$str = '<table class="zz" cellpadding="3" cellspacing="1" border="0" width="70%">';
	if(is_array($data))
	{
		foreach($data as $v)
		{
			$str .= '<tr class="bj-color0'.(($v['offset']%2)+1).'"><td>'.$v['fname_en'].' ('.$v['fname_cn'].')<input type="checkbox" name="function_id[]" value="'.$v['fid'].'" id="item_'.$v['fid'].'" /></td>';
			if(!empty($v['child']))
			{
				$str .= '<td>'.treeTable($v['child']).'</td>';
			}
			$str .= '</tr>';
		}
	}
	$str .= '</table>';
	return $str;
}

function getPageLink($total,$limit_str = "limit=20",$offset_str = "offset=0",$origin_arg = "",$page_per_page = 5,$pre_page="上一页",$next_page="下一页")
{
	if($pre_page=='上一页')
	{
		$first_page='首页';
		$last_page='末页';
	}
	else
	{
		$first_page='first page';
		$last_page='last page';
	}

	if (strlen($offset_str) > 0) {
		parse_str($offset_str, $offset_array);
		list($offset_name, $offset) = each($offset_array);
	} else {
		$offset = 0;
		$offset_name = "offset";
	}
	if (strlen($limit_str) > 0) {
		parse_str($limit_str, $limit_array);
		list($limit_name, $limit) = each($limit_array);
	} else {
		$limit = 10;
		$limit_name = "limit";
	}

	$page_total = ceil($total / $limit);

	if($offset-$limit>0)
		$prev_offset=$offset-$limit;		
	else
		$prev_offset=0;
	if($offset+$limit>=$total)
		$next_offset=$offset;
	else
		$next_offset=$offset+$limit;

	$page_current = (int)($offset / $limit)+1;
	if($page_per_page%2==1)
		$hnum=($page_per_page-1)/2;
	else
		$hnum=($page_per_page)/2;

	if($page_current-$hnum<1)
		$page_start=1;
	else
		$page_start=$page_current-$hnum;
	if($page_current+$hnum>$page_total)
	{
		$page_end=$page_total;
	}
	else
	{
		$page_end=$page_current+$hnum;
	}

	$output = '<table border="0" align="center" cellpadding="0" cellspacing="5"><tr>';
	$post_str = $origin_arg."&$limit_name=$limit&$offset_name=$prev_offset";
	$first_str=$origin_arg."&$limit_name=$limit&$offset_name=0";
	$last_offset=($page_total-1)*$limit;
	$last_offset=$last_offset>=0?$last_offset:0;
	$last_str=$origin_arg."&$limit_name=$limit&$offset_name=".$last_offset;

	$output .= '<td><a href="javascript:location.href=\'?'.$first_str.'\'">'.$first_page.'&lt;</a></td>';
	$output .= '<td><a href="javascript:location.href=\'?'.$post_str.'\'">'.$pre_page.'&lt;</a></td>';

	$output .= '<td class="ss" align="center"><div align="center"> ';
	for ($i = $page_start; $i <= $page_end; $i++) 
	{
		$post_str = $origin_arg."&$limit_name=$limit&$offset_name=".(($i - 1) * $limit);
		if ($i != $page_current)
		{
			$output .= '<a href="javascript:location.href=\'?'.$post_str.'\'">';
			$output .= $i;
			$output .= '</a> ';
		}
		else
		{
			$output .= "<span>$i</span> ";
		}
	}
	$output .= '</div></td>';

	$post_str = $origin_arg."&$limit_name=$limit&$offset_name=$next_offset";
	$output .= '<td><a href="javascript:location.href=\'?'.$post_str.'\'">&gt;'.$next_page.'</a></td>';
	$output .= '<td><a href="javascript:location.href=\'?'.$last_str.'\'">&gt;'.$last_page.'</a></td>';
	$output .= '</tr></table>';
	return $output;
}

/*
function add_s(&$array)
{
	if(!get_magic_quotes_gpc())
	{
		foreach($array as $key=>$value)
		{
			if(!is_array($value))
			{
				$array[$key]=addslashes($value);
			}
			else
			{
				add_s($array[$key]);
			}
		}
	}
}
*/
function fileFormat($fname)
{
	$tmp=trim($fname);
	$hz=substr(strrchr($tmp,"."),1);
	return strtolower($hz);
}

/*
 * 显示表格数据
 * title:表格表头,操作列放最后一列
 * control:操作列数组
 * cb:回调函数
 */
function showTable($data,$title,$control=false,$cb=false)
{
	if(!$data || !$title || !is_array($data) || !is_array($title))
		return;
	$rtn='<table class="zz" cellpadding="3" cellspacing="1" border="0" width="100%"><tr class="lb_tit">';
	$hasc=false;
	foreach($title as $k=>$v)
	{
		$rtn.='<td>'.$v.'</td>';
	}	
	if($control && is_array($control))
	{
		$hasc=true;
		$rtn.='<td>操作</td>';
	}
	$rtn.='</tr>';
	$len=count($data);
	foreach($data as $row)
	{
		$rtn.='<tr>';
		if($cb)
		{
			$cb($row);
		}
		foreach($title as $k=>$v)
		{
			$rtn.='<td>'.$row[$k].'</td>';
		}
		if($hasc)
		{
			$rtn.='<td>';
			foreach($control as $k1=>$v1)
			{
				$rtn.=showUrl($k1,$v1['url'],($v1['priname']?$v1['priname']:$v1['prikey']).'='.$row[$v1['prikey']].($v1['param']?'&'.$v1['param']:''),($v1['cb']?$v1['cb']:''));
			}
			$rtn.='</td>';
		}
		$rtn.='</tr>';
	}
	return $rtn.='</table>';
}
